@echo off
REM 构建脚本 - Windows版本
REM 使用方法: build.bat [debug|release|clean|run]

setlocal enabledelayedexpansion

REM 设置全局变量
set PROJECT_DIR=%~dp0
set BUILD_DIR=%PROJECT_DIR%build
set TARGET_NAME=CoroutineTest

REM 跳转到脚本入口点
goto :script_entry

REM 颜色定义 (Windows 10+ 支持ANSI颜色)
set GREEN=[32m
set YELLOW=[33m
set RED=[31m
set NC=[0m

REM 打印函数
:print_info
echo %GREEN%[INFO]%NC% %~1
goto :eof

:print_warning
echo %YELLOW%[WARNING]%NC% %~1
goto :eof

:print_error
echo %RED%[ERROR]%NC% %~1
goto :eof

REM 检查依赖
:check_dependencies
cmake --version >nul 2>&1
if errorlevel 1 (
    call :print_error "CMake not found, please install CMake"
    exit /b 1
)

REM 检查构建工具 - 既然项目已经构建过，使用cmake直接构建
set BUILD_CMD=cmake
set BUILD_FILE=
goto :eof

REM 清理构建目录
:clean_build
call :print_info "清理构建目录..."
if exist "%BUILD_DIR%" (
    rmdir /s /q "%BUILD_DIR%"
    call :print_info "构建目录已清理"
) else (
    call :print_info "构建目录不存在，无需清理"
)
goto :eof

REM 配置CMake
:configure_cmake
set build_type=%1
call :print_info "配置CMake (构建类型: %build_type%)..."

if not exist "%BUILD_DIR%" mkdir "%BUILD_DIR%"
cd /d "%BUILD_DIR%"

cmake -DCMAKE_BUILD_TYPE=%build_type% -DCMAKE_EXPORT_COMPILE_COMMANDS=ON "%PROJECT_DIR%"
if errorlevel 1 (
    call :print_error "CMake配置失败"
    exit /b 1
)

call :print_info "CMake配置完成"
goto :eof

REM 编译项目
:build_project
set build_type=%1
call :print_info "开始编译..."
cd /d "%BUILD_DIR%"

REM 使用CMake构建
cmake --build . --config %build_type%

if errorlevel 1 (
    call :print_error "编译失败"
    exit /b 1
)

call :print_info "编译完成"
call :print_info "可执行文件位置: %BUILD_DIR%\bin\Debug(Release)\%TARGET_NAME%.exe"
goto :eof

REM 运行项目
:run_project
REM 重新设置变量（处理作用域问题）
set PROJECT_DIR=%~dp0
set BUILD_DIR=%PROJECT_DIR%build
set TARGET_NAME=CoroutineTest

call :print_info "运行项目..."
if not exist "%BUILD_DIR%\bin\Debug\%TARGET_NAME%.exe" (
    if not exist "%BUILD_DIR%\bin\Release\%TARGET_NAME%.exe" (
        call :print_error "可执行文件不存在，请先构建项目"
        exit /b 1
    ) else (
        "%BUILD_DIR%\bin\Release\%TARGET_NAME%.exe"
    )
) else (
    "%BUILD_DIR%\bin\Debug\%TARGET_NAME%.exe"
)
goto :eof

REM 主函数
:main
set action=%1
if "%action%"=="" set action=debug

if "%action%"=="debug" (
    call :print_info "开始Debug构建..."
    call :clean_build
    call :configure_cmake Debug
    call :build_project Debug
    call :run_project
) else if "%action%"=="release" (
    call :print_info "开始Release构建..."
    call :clean_build
    call :configure_cmake Release
    call :build_project Release
    call :run_project
) else if "%action%"=="clean" (
    call :clean_build
) else if "%action%"=="run" (
    call :run_project
) else (
    call :print_error "未知参数: %action%"
    echo 使用方法: %~nx0 [debug^|release^|clean^|run]
    echo   debug   - Debug构建并运行 (默认^)
    echo   release - Release构建并运行
    echo   clean   - 清理构建目录
    echo   run     - 运行已构建的项目
    exit /b 1
)
goto :eof

REM 脚本入口
:script_entry
REM 首先检查依赖
call :check_dependencies
if errorlevel 1 exit /b 1

REM 执行主函数
call :main %*
